//
//  EmailViewModel.m
//  RACExample
//
//  Created by 山刘 on 2019/8/29.
//  Copyright © 2019 山刘. All rights reserved.
//

#import "EmailViewModel.h"

static NSString *const kSubscribeURL = @"http://reactivetest.apiary.io/subscribers";

@interface EmailViewModel()
@property(nonatomic, strong) RACSignal *emailValidSignal;
@end


@implementation EmailViewModel
-(instancetype)init{
    if (self == [super init]) {
        [self mapSubscribeCommandStateToStatusMessage];
    }
    return self;
}

- (void)mapSubscribeCommandStateToStatusMessage{
    RACSignal * rac1 = [self.subscribeCommand.executionSignals map:^id _Nullable(RACSignal* signal) {
        return @"Request";
    }];
    RACSignal *rac2 = [self.subscribeCommand.executionSignals flattenMap:^__kindof RACSignal * _Nullable(RACSignal* signal) {
        return [[[signal materialize]filter:^BOOL(RACEvent *event) {
            NSLog(@"...");
            return event.eventType == RACEventTypeCompleted;
        }] map:^id _Nullable(id  _Nullable value) {
            return @"Thanks!";
        }];
    }];
    RACSignal *rac3 = [[self.subscribeCommand.errors subscribeOn:[RACScheduler mainThreadScheduler]] map:^id _Nullable(NSError * _Nullable value) {
        return @"Error";
    }];
    RAC(self,statusMessage) = [RACSignal merge:@[rac1,rac2,rac3]];
}

-(RACCommand *)subscribeCommand{
    if (!_subscribeCommand) {
        @weakify(self)
        
        /*
         enabledSignal：这是指一个Bool值的信号(signal),指示是否要启动RACCommand命令。`enabled`是基于信号(signal)发送过来的最新的值，在之前信号(signal)发送过来的任何值，`enabled`都会被默认成YES。
         signalBlock: 这是个block，返回的信号(RACSignal)会被发送到`executionSignals`属性里。
         - (instancetype)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal<id> * (^)(id input))signalBlock
         
         subscribeCommand 和外部按钮的rac_command关联，当信号源处理返回状态不符合条件时，按钮置灰
         */
        _subscribeCommand = [[RACCommand alloc] initWithEnabled:self.emailValidSignal signalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self)
            return [EmailViewModel postEmail:self.email];
        }];
    }
    return _subscribeCommand;
}

+ (RACSignal *)postEmail:(NSString *)email {
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"Loading..."];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [subscriber sendError:nil];
        });
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [subscriber sendCompleted];
//        });
        return nil;
    }];
}

/**
 通过TextField传入的值和email绑定，在viewModel中创建一个信号源RACSignal，这样emailValidSignal就相当于一个具备电能的发电厂。
 */
-(RACSignal *)emailValidSignal{
    if (!_emailValidSignal) {
        _emailValidSignal = [RACObserve(self, email) map:^id _Nullable(NSString *email) {
            return @([email isValidEmail]);
        }];
    }
    return _emailValidSignal;
}
@end
